from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.utils import timezone
import uuid
from django.db.models.signals import post_save
from django.dispatch import receiver
from .feishu_service import FeishuService

class Project(models.Model):
    """项目空间模型"""
    name = models.CharField(
        _('项目名称'), 
        max_length=100, 
        help_text=_('请输入项目名称')
    )
    description = models.TextField(
        _('项目描述'), 
        blank=True, 
        null=True, 
        help_text=_('请输入项目描述')
    )
    webhook_messages = models.JSONField(
        _('Webhook消息'),
        default=list,
        blank=True,
        help_text=_('存储从Webhook接收到的消息')
    )
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, 
        on_delete=models.CASCADE, 
        related_name='created_projects',
        verbose_name=_('创建者')
    )
    created_at = models.DateTimeField(
        _('创建时间'), 
        auto_now_add=True
    )
    updated_at = models.DateTimeField(
        _('更新时间'), 
        auto_now=True
    )
    
    class Meta:
        verbose_name = _('项目空间')
        verbose_name_plural = _('项目空间')
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name

class ProjectMember(models.Model):
    """项目成员模型 - 用于权限控制"""
    ROLE_CHOICES = (
        ('admin', _('管理员')),
        ('developer', _('程序员')),
        ('operator', _('运营')),
    )
    
    project = models.ForeignKey(
        'Project', 
        on_delete=models.CASCADE, 
        related_name='members',
        verbose_name=_('项目')
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, 
        on_delete=models.CASCADE, 
        related_name='project_memberships',
        verbose_name=_('用户')
    )
    role = models.CharField(
        _('角色'), 
        max_length=10, 
        choices=ROLE_CHOICES, 
        default='operator'
    )
    joined_at = models.DateTimeField(
        _('加入时间'), 
        auto_now_add=True
    )
    
    class Meta:
        verbose_name = _('项目成员')
        verbose_name_plural = _('项目成员')
        unique_together = ('project', 'user')
    
    def __str__(self):
        return f'{self.user.username} - {self.project.name} - {self.get_role_display()}'

class ProjectTag(models.Model):
    """项目标签模型"""
    name = models.CharField(
        _('标签名称'), 
        max_length=50, 
        help_text=_('请输入标签名称')
    )
    color = models.CharField(
        _('标签颜色'), 
        max_length=20, 
        default='#1677ff',  # 默认蓝色
        help_text=_('请输入十六进制颜色值，如：#1677ff')
    )
    project = models.ForeignKey(
        'Project', 
        on_delete=models.CASCADE, 
        related_name='tags',
        verbose_name=_('项目')
    )
    
    class Meta:
        verbose_name = _('项目标签')
        verbose_name_plural = _('项目标签')
        unique_together = ('project', 'name')
    
    def __str__(self):
        return f'{self.name} ({self.project.name})'


class Announcement(models.Model):
    """公告模型"""
    title = models.CharField(
        _('公告标题'),
        max_length=200,
        help_text=_('请输入公告标题')
    )
    
    content = models.TextField(
        _('公告内容'),
        help_text=_('请输入公告内容')
    )
    
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='created_announcements',
        verbose_name=_('创建者')
    )
    
    created_at = models.DateTimeField(
        _('创建时间'),
        auto_now_add=True
    )
    
    is_active = models.BooleanField(
        _('是否激活'),
        default=True,
        help_text=_('设置为关闭则不会发送给新项目')
    )
    
    tags = models.ManyToManyField(
        'ProjectTag',
        blank=True,
        related_name='announcements',
        verbose_name=_('目标标签'),
        help_text=_('选择要发送公告的项目标签，留空则发送给所有项目')
    )
    
    class Meta:
        verbose_name = _('公告')
        verbose_name_plural = _('公告')
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title


class Message(models.Model):
    """消息模型 - 统一管理公告消息和webhook消息"""
    MESSAGE_TYPES = (
        ('announcement', _('公告消息')),
        ('webhook', _('Webhook消息')),
    )
    
    STATUS_CHOICES = (
        ('pending', _('未处理')),
        ('processed', _('已处理')),
    )
    
    project = models.ForeignKey(
        'Project',
        on_delete=models.CASCADE,
        related_name='messages',
        verbose_name=_('所属项目')
    )
    
    message_type = models.CharField(
        _('消息类型'),
        max_length=20,
        choices=MESSAGE_TYPES,
        help_text=_('消息类型：公告消息或Webhook消息')
    )
    
    title = models.CharField(
        _('标题'),
        max_length=500,
        help_text=_('消息标题')
    )
    
    content = models.TextField(
        _('内容'),
        help_text=_('消息内容')
    )
    
    status = models.CharField(
        _('状态'),
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        help_text=_('消息处理状态')
    )
    
    source_data = models.JSONField(
        _('原始数据'),
        default=dict,
        blank=True,
        help_text=_('存储原始消息数据')
    )
    
    processed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='processed_messages',
        verbose_name=_('处理人')
    )
    
    processed_at = models.DateTimeField(
        _('处理时间'),
        null=True,
        blank=True
    )
    
    created_at = models.DateTimeField(
        _('创建时间'),
        auto_now_add=True
    )
    
    updated_at = models.DateTimeField(
        _('更新时间'),
        auto_now=True
    )
    
    class Meta:
        verbose_name = _('消息')
        verbose_name_plural = _('消息')
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['project', 'status']),
            models.Index(fields=['message_type', 'status']),
            models.Index(fields=['created_at']),
        ]
    
    def __str__(self):
        return f"{self.get_message_type_display()} - {self.title}"
    
    def mark_as_processed(self, user):
        """标记消息为已处理"""
        self.status = 'processed'
        self.processed_by = user
        self.processed_at = timezone.now()
        self.save()
        
        # 记录处理历史
        MessageProcessingHistory.objects.create(
            message=self,
            action='processed',
            performed_by=user,
            notes=f"消息被 {user.username} 标记为已处理"
        )

    def mark_as_pending(self, user=None):
        """标记消息为未处理"""
        self.status = 'pending'
        self.processed_by = None
        self.processed_at = None
        self.save()
        
        # 记录处理历史
        if user:
            MessageProcessingHistory.objects.create(
                message=self,
                action='pending',
                performed_by=user,
                notes=f"消息被 {user.username} 标记为未处理"
            )

    def add_note(self, user, note_content):
        """添加备注信息"""
        return MessageNote.objects.create(
            message=self,
            author=user,
            content=note_content
        )
    
    @property
    def is_processed(self):
        """是否已处理"""
        return self.status == 'processed'
    
    @property
    def is_pending(self):
        """是否未处理"""
        return self.status == 'pending'


class Webhook(models.Model):
    """项目Webhook模型"""
    # 支持的事件类型
    EVENT_CHOICES = (
        ('alarm', _('报警信息')),
        ('announcement', _('公告信息')),
        ('push', _('推送')),
    )
    
    # 支持的接收渠道
    CHANNEL_CHOICES = (
        ('platform', _('平台')),
        ('feishu', _('飞书')),
        ('wework', _('企业微信')),
    )
    
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        verbose_name=_('Webhook ID')
    )
    
    project = models.ForeignKey(
        'Project',
        on_delete=models.CASCADE,
        related_name='webhooks',
        verbose_name=_('项目')
    )
    
    name = models.CharField(
        _('Webhook名称'),
        max_length=100,
        help_text=_('请输入Webhook名称，用于识别不同的Webhook')
    )
    
    url = models.URLField(
        _('Webhook URL'),
        max_length=500,
        help_text=_('请输入接收Webhook通知的URL地址')
    )
    
    secret = models.CharField(
        _('签名密钥'),
        max_length=255,
        blank=True,
        null=True,
        help_text=_('用于验证Webhook请求的签名密钥，留空则不进行签名验证')
    )
    
    events = models.JSONField(
        _('触发事件'),
        help_text=_('选择哪些事件会触发Webhook通知'),
        default=list
    )
    
    is_active = models.BooleanField(
        _('是否激活'),
        default=True,
        help_text=_('设置为关闭则不会发送任何Webhook通知')
    )
    
    channel = models.CharField(
        _('渠道'),
        max_length=20,
        choices=CHANNEL_CHOICES,
        default='platform',
        help_text=_('选择Webhook通知的渠道')
    )
    
    created_at = models.DateTimeField(
        _('创建时间'),
        auto_now_add=True
    )
    
    updated_at = models.DateTimeField(
        _('更新时间'),
        auto_now=True
    )
    
    last_triggered_at = models.DateTimeField(
        _('最后触发时间'),
        blank=True,
        null=True,
        help_text=_('记录Webhook最后一次触发的时间')
    )
    
    class Meta:
        verbose_name = _('项目Webhook')
        verbose_name_plural = _('项目Webhooks')
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.name} ({self.project.name})'


class MessageProcessingHistory(models.Model):
    """消息处理历史记录模型"""
    ACTION_CHOICES = (
        ('created', _('创建')),
        ('processed', _('标记已处理')),
        ('pending', _('标记未处理')),
        ('note_added', _('添加备注')),
    )
    
    message = models.ForeignKey(
        Message,
        on_delete=models.CASCADE,
        related_name='processing_history',
        verbose_name=_('消息')
    )
    
    action = models.CharField(
        _('操作类型'),
        max_length=20,
        choices=ACTION_CHOICES,
        help_text=_('执行的操作类型')
    )
    
    performed_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='message_processing_actions',
        verbose_name=_('执行人')
    )
    
    performed_at = models.DateTimeField(
        _('执行时间'),
        auto_now_add=True
    )
    
    notes = models.TextField(
        _('操作说明'),
        blank=True,
        help_text=_('操作的具体说明')
    )
    
    class Meta:
        verbose_name = _('消息处理历史')
        verbose_name_plural = _('消息处理历史')
        ordering = ['-performed_at']
    
    def __str__(self):
        return f"{self.message.title} - {self.get_action_display()} by {self.performed_by.username}"


class MessageNote(models.Model):
    """消息备注模型"""
    message = models.ForeignKey(
        Message,
        on_delete=models.CASCADE,
        related_name='notes',
        verbose_name=_('消息')
    )
    
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='message_notes',
        verbose_name=_('作者')
    )
    
    content = models.TextField(
        _('备注内容'),
        help_text=_('请输入备注信息')
    )
    
    created_at = models.DateTimeField(
        _('创建时间'),
        auto_now_add=True
    )
    
    updated_at = models.DateTimeField(
        _('更新时间'),
        auto_now=True
    )
    
    class Meta:
        verbose_name = _('消息备注')
        verbose_name_plural = _('消息备注')
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.message.title} - Note by {self.author.username}"
    
    def clean(self):
        """验证备注内容"""
        if not self.content.strip():
            raise ValidationError(_('备注内容不能为空'))
    
    def save(self, *args, **kwargs):
        """保存前进行验证并记录历史"""
        is_new = self.pk is None
        super().save(*args, **kwargs)
        
        # 如果是新备注，记录处理历史
        if is_new:
            MessageProcessingHistory.objects.create(
                message=self.message,
                action='note_added',
                performed_by=self.author,
                notes=f"添加了备注: {self.content[:50]}..."
            )


@receiver(post_save, sender=Message)
def message_post_save(sender, instance, created, **kwargs):
    """
    消息保存后的信号处理
    当新消息创建时，自动推送到飞书
    """
    if created:  # 只在创建新消息时触发
        try:
            if instance.message_type == 'announcement':
                # 获取对应的公告对象
                announcement = Announcement.objects.filter(
                    title=instance.title,
                    content=instance.content
                ).first()
                if announcement:
                    FeishuService.send_announcement_notification(
                        instance.project, 
                        announcement
                    )
            elif instance.message_type == 'webhook':
                FeishuService.send_webhook_message_notification(
                    instance.project, 
                    instance
                )
        except Exception as e:
            logger.error(f"飞书消息推送失败: {str(e)}")
